package yiranyousheng.com.alarm_r;

import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.text.TextUtils;
import android.text.format.DateUtils;
import android.view.View;
import android.widget.CheckedTextView;
import android.widget.CompoundButton;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import android.widget.ToggleButton;

import java.util.Calendar;
import java.util.HashSet;
import java.util.Set;


public class AlarmActivity extends ActionBarActivity {

    private TimePicker timePicker;
    private CheckedTextView monday,tuesday,wednesday,thursday,friday,saturday,sunday;
    private TextView ringtone,tips;
    private MediaPlayer player;
    private ImageButton palyButton;
    private ToggleButton toggleButton ;
    private SharedPreferences sharedPreferences;
    private  Set<String> repeats;
    public   static  final  String ALARM_ENABLE = "alarm_enable";
    public  static  final  String ALARM_TIME = "alarm_time";
    public  static  final  String ALARM_REPEAT= "alarm_repeat";
    public  static  final  String ALARM_URI = "alarm _uri";
    public  static  final  String ALARM_TITLe = "alarm _title";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_alarm);
        // 或许当前的年月日，小时，分钟
        Calendar ca = Calendar.getInstance();
//        int   year = ca.get(Calendar.YEAR);
//        int month = ca.get(Calendar.MONTH);
//        int  day = ca.get(Calendar.DAY_OF_MONTH);
        final int hour = ca.get(Calendar.HOUR_OF_DAY);
        int minute = ca.get(Calendar.MINUTE);

        timePicker = (TimePicker)findViewById(R.id.timePicker);
        timePicker.setIs24HourView(true);
        timePicker.setCurrentMinute(minute);
        timePicker.setCurrentHour(hour);
        timePicker.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener() {
            @Override
            public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {

                tips.setText(getAlarminfo(calculteAlarmTime(timePicker.getCurrentHour(), timePicker.getCurrentMinute())));
            }
        });


        monday = (CheckedTextView) findViewById(R.id.Monday);
        tuesday = (CheckedTextView) findViewById(R.id.Tuesday);
        wednesday = (CheckedTextView) findViewById(R.id.Wednesday);
        thursday = (CheckedTextView) findViewById(R.id.Thursday);
        friday = (CheckedTextView) findViewById(R.id.Friday);
        saturday = (CheckedTextView) findViewById(R.id.Saturday);
        sunday = (CheckedTextView) findViewById(R.id.Sunday);

//
        monday.setOnClickListener(clickListener);
        tuesday.setOnClickListener(clickListener);
        wednesday.setOnClickListener(clickListener);
        thursday.setOnClickListener(clickListener);
        friday.setOnClickListener(clickListener);
        saturday.setOnClickListener(clickListener);
        sunday.setOnClickListener(clickListener);



        palyButton = (ImageButton)findViewById(R.id.play);
        palyButton.setOnClickListener(clickListener);
        ringtone = (TextView) findViewById(R.id.ringtone);
        ringtone.setOnClickListener(clickListener);
        tips = (TextView)findViewById(R.id.tips);
        findViewById(R.id.save).setOnClickListener(clickListener);
        findViewById(R.id.cancel).setOnClickListener(clickListener);

        sharedPreferences = getSharedPreferences("settings", MODE_PRIVATE);
        repeats = sharedPreferences.getStringSet(ALARM_REPEAT,new HashSet<String>());
        if(repeats.size()>1){
            monday.setChecked(repeats.contains(monday.getTag().toString()));
            tuesday.setChecked(repeats.contains(tuesday.getTag().toString()));
            wednesday.setChecked(repeats.contains(wednesday.getTag().toString()));
            thursday.setChecked(repeats.contains(thursday.getTag().toString()));
            friday.setChecked(repeats.contains(friday.getTag().toString()));
            saturday.setChecked(repeats.contains(saturday.getTag().toString()));
            sunday.setChecked(repeats.contains(sunday.getTag().toString()));
        }

        toggleButton = (ToggleButton) findViewById(R.id.toggle);
        toggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                timePicker.setAlpha(isChecked ? 1 : 0.5f);
                timePicker.setEnabled(isChecked);
            }
        });

        findViewById(R.id.message).setOnClickListener(clickListener);

        init();
    }

    @Override
    protected void onResume() {
        super.onResume();


    }

    private void init() {
        if (!sharedPreferences.getBoolean(ALARM_ENABLE,false)){
            tips.setText(getAlarminfo(null));
        }else{
            Calendar c = Calendar.getInstance();
            c.setTimeInMillis(sharedPreferences.getLong(ALARM_TIME,0L));
            tips.setText(getAlarminfo(c));
        }
        ringtone.setText(sharedPreferences.getString(ALARM_TITLe, "请选择铃声"));

        toggleButton.setChecked(sharedPreferences.getBoolean(ALARM_ENABLE, false));
    }

    private Calendar  calculteAlarmTime(int hourOfDay,int minute) {
        Calendar cal = Calendar.getInstance();
        int calHour = cal.get(Calendar.HOUR_OF_DAY);
        int calMin = cal.get(Calendar.MINUTE);


        if(hourOfDay<calHour ||(hourOfDay == calHour && minute < calMin) ||(hourOfDay == calHour && calMin == minute)) cal.add(Calendar.DATE, 1);
        cal.set(Calendar.HOUR_OF_DAY, hourOfDay);
        cal.set(Calendar.MINUTE, minute);
        return  cal;
    }

    String getAlarminfo(Calendar cal){
        if (cal == null) return  "请设置闹铃";
        return  DateUtils.getRelativeTimeSpanString(cal.getTimeInMillis(),System.currentTimeMillis(),
                DateUtils.SECOND_IN_MILLIS).toString()+"响铃";

    }

    private View.OnClickListener clickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            System.out.println("clickListener");
            switch (v.getId()){
                case R.id.ringtone:
                    stopPlay();
                    Intent intent = new Intent(RingtoneManager.ACTION_RINGTONE_PICKER);
                    //设置铃声类型和title
                    intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TYPE, RingtoneManager.TYPE_ALARM);
                    intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TITLE, "设置闹铃铃声");
                    //当设置完成之后返回到当前的Activity
                    startActivityForResult(intent, 3);
                    return;
                case R.id.play:
                    if(player!=null && player.isPlaying()){
                        stopPlay();
                    }else {
                        play(Uri.parse(sharedPreferences.getString(ALARM_URI,"")));
                    }

                    return;
                case  R.id.message:
                    new AlertDialog.Builder(AlarmActivity.this)
                            .setIcon(R.drawable.msp_edit_warning)
                            .setTitle("注意")
                            .setMessage(R.string.message)
                            .show();
                    return;
                case  R.id.save:
                    save();
                    finish();
                 return;
                case  R.id.cancel:
                    finish();
                    return;
            }
            CheckedTextView ct = (CheckedTextView) v;
            ct.setChecked(!ct.isChecked());

        }


    };

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != RESULT_OK || requestCode != 3) {
            return;
        }
        try {
            Uri pickedUri = data.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI); //获取选择的URI
            Toast.makeText(this, pickedUri.toString(), Toast.LENGTH_LONG).show();
            Ringtone selectedRingtone =  RingtoneManager.getRingtone(AlarmActivity.this, pickedUri);
            String title =  selectedRingtone.getTitle(this);

            if (TextUtils.isEmpty(title)){
                ringtone.setText(pickedUri.toString());
            }else{
                ringtone.setText(title);
            }
            sharedPreferences.edit().putString(ALARM_URI,pickedUri.toString()).commit();
            sharedPreferences.edit().putString(ALARM_TITLe, title).commit();

            System.out.println("onActivityResult =" + selectedRingtone.getTitle(this));
        } catch (Exception e) {  }
    }

    private void play(Uri pickUri){
        if(TextUtils.isEmpty(pickUri.toString())) return;
        palyButton.setBackgroundResource(R.drawable.videoplayer_icon_stop_highlighted);
        player= new MediaPlayer();
        try{
            player.setDataSource(this, pickUri);
        }catch(Exception e){
            e.printStackTrace();
        }
        final AudioManager audioManager = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
        if(audioManager.getStreamVolume(AudioManager.STREAM_ALARM)!=0){
            player.setAudioStreamType(AudioManager.STREAM_ALARM);
            player.setLooping(true);
            try {
                player.prepare();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            player.start();
        }else{
            Toast.makeText(this,"当前闹钟音量静音，请重新设置",Toast.LENGTH_SHORT).show();
        }

    }
    private void stopPlay(){
        if (player==null) return;;
        palyButton.setBackgroundResource(R.drawable.videoplayer_icon_play_highlighted);
        player.stop();
        player.release();
        player = null;
    }

     void saveRepeat(){
         repeats.clear();
         repeats.add(getFlage(monday));
         repeats.add(getFlage(tuesday));
         repeats.add(getFlage(thursday));
         repeats.add(getFlage(wednesday));
         repeats.add(getFlage(friday));
         repeats.add(getFlage(saturday));
         repeats.add(getFlage(sunday));

        sharedPreferences.edit().putStringSet(ALARM_REPEAT,repeats).commit();

    }

    private String getFlage(CheckedTextView checkedTextView) {
        if (checkedTextView.isChecked()) return checkedTextView.getTag().toString();
        return "";
    }

    private void saveTime() {
        sharedPreferences.edit().putBoolean(ALARM_ENABLE,toggleButton.isChecked()).commit();
        Calendar calendar = calculteAlarmTime(timePicker.getCurrentHour(),timePicker.getCurrentMinute());
        if(toggleButton.isChecked())
            sharedPreferences.edit().putLong(ALARM_TIME,calendar.getTimeInMillis()).commit();
        else
            sharedPreferences.edit().remove(ALARM_TIME).commit();
    }
    private void createAlarm(boolean flag) {
        AlarmManager alarmMgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent(getApplicationContext(), AlarmReceiver.class);
        int requestCode = 0;
        PendingIntent pendIntent = PendingIntent.getBroadcast(getApplicationContext(),
                requestCode, intent,0);

       if (flag){
           alarmMgr.set(AlarmManager.RTC_WAKEUP,sharedPreferences.getLong(ALARM_TIME, 0L) , pendIntent);
           Toast.makeText(this,"闹铃创建成功",Toast.LENGTH_LONG).show();
       }else{
           alarmMgr.cancel(pendIntent);
           Toast.makeText(this,"闹铃已经关闭",Toast.LENGTH_LONG).show();
       }
    }

    /**
     * 创建定时器
     */
    private void save() {
        //TODO
        saveTime();
        saveRepeat();
        createAlarm(toggleButton.isChecked());
    }





}
